import React, { PureComponent } from 'react';
import {
  Row,
  Col,
  Input,
  Spin,
  Upload,
  Descriptions,
  Button,
  Icon,
  message,
  Card,
  Tabs,
} from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import FileBtn from '@/components/FileBtn';
import PageEmpty from '@/components/PageEmpty';
import qs from 'qs';
import styles from './index.less';
import { getPageQuery, showConfirm } from '@/utils/utils';
import { createUploadUsingPOST } from '@/services/upload';
import AnnualIndicators from './components/AnnualIndicators';
import MonthlyIndex from './components/MonthlyIndex';
import Difference from './components/Difference';
import * as api from '@/services/ValueApprovelMgr';

const { TextArea } = Input;
const { Dragger } = Upload;
const { TabPane } = Tabs;

@connect(state => ({
  item: state.SigningApprove.item,
  // currentUser: state.user.currentUser,
}))
class Approve extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      description: '',
      fileLoading: false,
      fileList: [],
      loading: false,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const queryParams = getPageQuery();
    if (queryParams && queryParams.token) {
      if (dispatch) {
        dispatch({
          type: 'token/save',
          payload: queryParams.token,
        });
      }
    }

    const { action, id, projectId } = location.query;
    if (!action) {
      const theHead = document.getElementsByTagName('head').item(0);
      // 创建脚本的dom对象实例
      const myScript = document.createElement('script');
      myScript.src = process.env.oaUrl;
      myScript.type = 'text/javascript';
      myScript.defer = true;
      theHead.appendChild(myScript);
    }
    const params = {
      projectId: projectId || '',
      billId: id || '',
    };
    if (dispatch) {
      dispatch({
        type: 'SigningApprove/init',
        payload: {
          params,
        },
        callback: data => {
          // if (id) {
          const { description, files } = data;

          const fileList = [];
          _.forEach(files, v => {
            fileList.push({
              uid: v.fileId,
              name: v.fileName,
              filePath: v.filePath,
              previewUrl: v.previewUrl,
              status: 'done',
            });
          });
          this.setState({
            description,
            fileList,
          });
          // }
          if (!action && window.cifioa) {
            window.cifioa.sendMessage({
              type: 'height',
              height: window.document.body.scrollHeight,
            });
          }
        },
      });
    }
  }

  handApprove() {
    const { dispatch, item, location } = this.props;
    const { id, projectId } = location.query;
    const { description, fileList } = this.state;
    if (!description) {
      message.warning('请填写审批要点说明');
      return;
    }
    const files = [];
    _.forEach(fileList, data => {
      files.push(data.uid);
    });
    this.setState({
      loading: true,
    });

    const data = {
      projectId: projectId || '',
      businessKey: id || '',
      businessType: 'signing_plan',
      description,
      files,
      overallVersionIds: item.overallVersionIds,
      pkVersionIds: item.pkVersionIds,
      versionTypeCode: item.organizationDto.versionTypeCode,
      organizationIds: item.organizationIds,
      yearMonth: item.yearMonth,
    };
    if (dispatch) {
      dispatch({
        type: 'SigningApprove/approved',
        payload: { data },
        callback: result => {
          if (result && result.code * 1 === 1) {
            window.location.href = `${result.data}`;
          }
          this.setState({
            loading: false,
          });
        },
      });
    }
  }

  // 删除文件
  removeFile(fileId, file) {
    const { fileList } = this.state;
    const newFileList = _.filter(fileList, data => data.uid !== file.uid);
    const { dispatch } = this.props;
    const params = {
      fileId,
    };
    dispatch({
      type: 'SigningApprove/deleteFile',
      payload: { params },
      callback: data => {
        if (data) {
          this.setState({
            fileList: newFileList,
          });
          message.success(`${data.message}`);
        }
      },
    });
  }

  // 获取审批要点
  saveDescription(e) {
    this.setState({
      description: e.target.value,
    });
  }

  /* 下载文件 */
  download({ uid }) {
    const params = {
      fileId: uid,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/fileUpload/download?${exportQueryString}`);
  }

  render() {
    const { action, taskId } = this.props.location.query;
    const { item } = this.props;
    const { loading, description, fileList, fileLoading } = this.state;

    let hasOaInstanceId = false;
    let isEdit = false;
    // 是否已有oa流程实例
    if (item && item.instanceId && item.instanceId !== '') {
      hasOaInstanceId = true;
    }
    // 是否是修改状态 action=modify
    if (action && action === 'modify') {
      isEdit = true;
    }
    // 是否是oa驳回门户待办 taskId=xxx
    if (taskId) {
      isEdit = true;
    }
    return (
      <div className={styles.approve} style={{ padding: action ? '0 100px' : '0' }}>
        {action ? (
          <div className={styles.headerTitle}>
            {item && item.organizationDto && item.organizationDto.topName}
          </div>
        ) : null}
        {!_.isEmpty(item) ? (
          <Card>
            {action ? (
              <div className="title">
                <i></i>
                <span>审批内容</span>
              </div>
            ) : null}
            {/* 基本信息 */}
            <Row gutter={[50, 10]}>
              <Col span={24}>
                <div className="sub-title">基本信息</div>
              </Col>
              <Col span={10}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="项目">{`${item.projectName} ( ${item.projectCode} )`}</Descriptions.Item>
                </Descriptions>
              </Col>
              <Col span={7}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="区域">{item.regionName}</Descriptions.Item>
                </Descriptions>
              </Col>
              <Col span={7}>
                <Descriptions size="small" title="" bordered>
                  <Descriptions.Item label="权益比例">{item.equityRatio * 1}%</Descriptions.Item>
                </Descriptions>
              </Col>
            </Row>
            {/* 本次编排版本 */}
            {item && item.organizationDto && item.organizationDto.stageNames.length > 0 ? (
              <Row gutter={[50, 10]}>
                <Col span={24}>
                  <div className="sub-title">本次编排版本 </div>
                </Col>
                {_.map(item.organizationDto.stageNames, value => (
                  <Col key={value} span={8}>
                    <Descriptions size="small" title="" bordered>
                      <Descriptions.Item label={value.split(':')[0]}>
                        <a
                          onClick={() => {
                            window.open(`${window.location.origin}/#/OperatingPlan/ContractPlan`);
                          }}
                        >
                          {value.split(':')[1]}
                        </a>
                      </Descriptions.Item>
                    </Descriptions>
                  </Col>
                ))}
              </Row>
            ) : null}
            {item && item.overallYearIndexList.length > 0 ? (
              <Row>
                <Col span={24} className="sub-title">
                  全盘年度指标
                </Col>
                <Col span={24}>
                  <Tabs>
                    {item.overallYearIndexList.map(element => (
                      <TabPane tab={element.year} key={element.year}>
                        <Row gutter={[0, 20]}>
                          <Col>
                            {`${element.year}年度指标`}
                            {/* {console.log(element.yearIndex, 'ssssssss')} */}
                            <AnnualIndicators yearIndex={element.yearIndex} year={element.year} />
                          </Col>
                          <Col>
                            {`${element.year}年月度指标`}
                            <MonthlyIndex
                              yearEarlyBottomList={element.yearEarlyBottomList}
                              year={element.year}
                            />
                          </Col>
                        </Row>
                      </TabPane>
                    ))}
                  </Tabs>
                </Col>
              </Row>
            ) : null}

            {/* 月均销售同比偏差 */}
            {item && item.monthSaleRateDeviationList.length > 0 ? (
              <Row>
                <Col span={24}>
                  <div className="sub-title">月均销售同比偏差</div>
                </Col>
                <Col span={24}>
                  <Difference {...item} />
                </Col>
              </Row>
            ) : null}
            {/* 审批要点说明 */}
            <Row>
              <Col span={24}>
                <div className="sub-title">审批要点说明</div>
              </Col>
              <Col span={24}>
                {!action ? (
                  <TextArea
                    rows={1}
                    autosize
                    maxLength={500}
                    disabled
                    value={item.description}
                    onChange={desc => this.saveDescription(desc)}
                  />
                ) : (
                  <TextArea
                    rows={1}
                    autosize
                    style={{ resize: 'none' }}
                    maxLength={500}
                    value={description}
                    onChange={desc => this.saveDescription(desc)}
                  />
                )}
              </Col>
            </Row>
            {/* 附件 */}
            <Row>
              <Col span={24}>
                {item.files && item.files.length > 0 ? <div className="sub-title">附件</div> : null}
              </Col>
              <Col span={24}>
                {action ? (
                  <Spin spinning={fileLoading} tip="上传中...">
                    <Dragger
                      action={file => {
                        const self = this;
                        const fromData = new FormData();
                        fromData.append('file', file);
                        if (file.size > 20480000) {
                          message.warning('单个文件最大上传20M.');
                          return;
                        }
                        self.setState({
                          fileLoading: true,
                        });
                        createUploadUsingPOST({ data: fromData }).then(data => {
                          if (data.code === 1) {
                            const newfileList = [
                              ...fileList,
                              {
                                uid: data.data.fileId,
                                name: data.data.fileName,
                                filePath: data.data.filePath,
                                previewUrl: data.data.previewUrl,
                                status: 'done',
                              },
                            ];
                            self.setState({
                              fileList: newfileList,
                              fileLoading: false,
                            });
                            if (!data.data.message) {
                              message.success(`${file.name} 上传成功`);
                            } else {
                              message.error(`${data.data.message} 请删除`);
                            }
                          }
                        });
                      }}
                      name="file"
                      multiple={false}
                      fileList={fileList}
                      onRemove={file => {
                        this.removeFile(file.uid, file);
                      }}
                      onDownload={file => this.download(file)}
                    >
                      <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                      </p>
                      <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                      <p className="ant-upload-hint">单个文件最大上传20M.</p>
                    </Dragger>
                  </Spin>
                ) : (
                  <>
                    {_.map(item.files, (element, key) => (
                      <FileBtn
                        fileId={element.fileId}
                        fileName={element.fileName}
                        clickType="textClick"
                        titleNmae
                        key={key}
                        download={true}
                      />
                    ))}
                  </>
                )}
              </Col>
            </Row>
            {isEdit ? (
              <Row type="flex" justify="center" gutter={[10]}>
                {/* 提交到OA审批 */}
                <Col>
                  <Button type="primary" loading={loading} onClick={() => this.handApprove()}>
                    提交到OA审批
                  </Button>
                </Col>
                {/* 返回修改 */}
                <Col>
                  <Button
                    onClick={() => {
                      window.location.href = `${window.location.origin}/#/OperatingPlan/ContractPlan`;
                    }}
                  >
                    返回修改
                  </Button>
                </Col>
                {/* 查看审批 (有流程实例) */}
                {hasOaInstanceId ? (
                  <Col>
                    <Button
                      type="primary"
                      onClick={() => {
                        window.location.href = item.reviewUrl;
                      }}
                    >
                      查看审批
                    </Button>
                  </Col>
                ) : null}
                {/* 废弃 (有流程实例) */}
                {hasOaInstanceId &&
                item.state &&
                (item.state === 'reject' || item.state === 'recall') ? (
                  <Col>
                    <Button
                      onClick={() => {
                        showConfirm(
                          () => {
                            api
                              .endFlowUsingPUT({
                                params: {
                                  instanceId: item.instanceId,
                                },
                              })
                              .then(result => {
                                message.loading('废弃流程中...', () => {
                                  if (result.code === 1) {
                                    message.success(result.message, () => {
                                      window.location.href = `${window.location.origin}/#/OperatingPlan/ContractPlan`;
                                    });
                                  }
                                });
                              });
                          },
                          '是否要废弃该流程?',
                          '确定后将作废该流程后返回签约计划',
                        );
                      }}
                    >
                      废弃
                    </Button>
                  </Col>
                ) : null}
                {/* 关闭 */}
                <Col>
                  <Button
                    className="red-button"
                    onClick={() => {
                      if (navigator.userAgent.includes('MSIE')) {
                        // close IE
                        if (navigator.userAgent.includes('MSIE 6.0')) {
                          window.opener = null;
                          window.close();
                        } else {
                          window.open('', '_top');
                          window.top.close();
                        }
                      } else {
                        // close chrome;It is effective when it is only one.
                        window.opener = null;
                        window.open('', '_self');
                        window.close();
                      }
                    }}
                  >
                    关闭
                  </Button>
                </Col>
              </Row>
            ) : null}
          </Card>
        ) : (
          <PageEmpty emptyTitle="加载中" />
        )}
      </div>
    );
  }
}
export default Approve;
